package org.zero.onlinesubject.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//@Component
@Slf4j
@Aspect
public class LogRecordAspect {

    @Pointcut("execution(* org.zero.onlinesubject.controller.*.*(..))")
    public void pt(){}

    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long time = System.currentTimeMillis() - start;
        recordLog(joinPoint,time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        String param = JSON.toJSONString(args);
        String methodName = method.getName();
        String className = joinPoint.getTarget().getClass().getName();
        log.info("======================== log start ========================");
        log.info("request method: {}",className+"."+methodName);
        log.info("params: {}",param);
        log.info("execute time {} ms",time);
        log.info("======================== log end ==========================");
    }
}
